//
//  ScanBindDeviceViewController.m
//  ForYourBeauty
//
//  Created by Kelly xu on 2019/5/27.
//  Copyright © 2019 changrenTech. All rights reserved.
//

#import "ScanBindDeviceViewController.h"
#import <NetworkExtension/NetworkExtension.h>
#import "DeviceViewModel.h"
#import "SmartLinkExportObject.h"
#import <SystemConfiguration/SystemConfiguration.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <MBProgressHUD/MBProgressHUD.h>
#import <NetworkExtension/NEHotspotConfigurationManager.h>
#import "WifiHotSpotListViewController.h"
#import "ApConfigWifiManager.h"
#import "WifiSettingViewController.h"
@interface ScanBindDeviceViewController ()<DeviceScanDelegate>
@property(nonatomic,weak)IBOutlet UIImageView *inputTextBg;
@property(nonatomic,weak)IBOutlet UIImageView *prdIcon;
@property(nonatomic,weak)IBOutlet UILabel *prdName;
@property(nonatomic,weak)IBOutlet UILabel *prdCode;
@property(nonatomic,weak)IBOutlet UIButton *searchBtn;
@property(nonatomic,weak)IBOutlet UITextField *wifiNameText;
@property(nonatomic,weak)IBOutlet UITextField *wifiPwdText;
@property(nonatomic,strong)DeviceViewModel *deviceInfoViewModel;
@property(nonatomic,strong)NSString *prdId;
@property(nonatomic,assign)BOOL configWifiSuc;
@property(nonatomic,assign)BOOL bindDeviceSuc;
@property(nonatomic,assign)BOOL isRequest;
@end

@implementation ScanBindDeviceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"扫码绑定";
    [self configUI];
}
- (void)leftbuttonPressed:(id)sender{
    [SVProgressHUD dismiss];
    [self.rt_navigationController popViewControllerAnimated:YES complete:nil];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (!self.isRequest) {
        self.isRequest = YES;
        [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        [self.deviceInfoViewModel fetchDeviceInfo:self.snCode cmp:^(NSDictionary * _Nonnull deviceInfo) {
            if ([deviceInfo isKindOfClass:[NSDictionary class]]) {
                self.prdName.text = [NSString stringWithFormat:@"%@",deviceInfo[@"deviceType"]];
                self.prdCode.text = [NSString stringWithFormat:@"%@",deviceInfo[@"deviceSn"]];
                self.prdId = [NSString stringWithFormat:@"%@",deviceInfo[@"id"]];
                if (!EC_ISNullStr(deviceInfo[@"wifiName"])) {
                    [self configWifiHotDot:deviceInfo[@"wifiName"]];
                }
            }else{
                Toast(@"没有扫描到设备");
                [self.rt_navigationController popToRootViewControllerAnimated:YES complete:nil];
            }
            [MBProgressHUD hideHUDForView:KeyWindow animated:YES];
        }];
    }
}
-(void)configWifiHotDot:(NSString*)wifiName{
    NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:wifiName passphrase:@"12345678" isWEP:NO];
    [SVProgressHUD show];
    [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
        NSLog(@"%@", error);
        if([[self getSSID]isEqualToString:wifiName]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                Toast(@"切换成功");
            });
            NSLog(@"加入网络成功");
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [self showWifiConfigErrorAlert];
            });
        }
    }];
}
-(IBAction)selectWifi:(id)sender{
    WifiHotSpotListViewController *hotspot = [[WifiHotSpotListViewController alloc]init];
    [self.rt_navigationController pushViewController:hotspot animated:YES complete:nil];
}
//获取wifi
#pragma mark - Datas
- (NSString*)getSSID {
    NSString*  ssidStr = [self fetchSSIDInfo][@"SSID"];
    if (ssidStr == nil || [ssidStr isEqualToString:@""]) {
        return @"";
    }else {
        return ssidStr ? :@"";
    }
}

/**
 *  获取SSID信息
 *
 *  @return id
 */
-(id)fetchSSIDInfo {
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        
        if (info && [info count]) {
            break;
        }
    }
    return info;
}
-(void)configUI{
    [self.inputTextBg setImage:[[UIImage imageNamed:@"cornerBg"] stretchableImageWithLeftCapWidth:[UIImage imageNamed:@"cornerBg"].size.width/2 topCapHeight:[UIImage imageNamed:@"cornerBg"].size.height/2]];
    self.searchBtn.layer.cornerRadius = 20;
}
-(IBAction)bindBtnPressed:(id)sender{
    if (self.wifiNameText.text.length == 0) {
        Toast(@"请输入wifi名称");
        return;
    }
    if (self.wifiPwdText.text.length == 0) {
        Toast(@"请输入wifi密码");
        return;
    }
    if (![[self getSSID] hasPrefix:@"CY"]) {
        [self showWifiConfigErrorAlert];
    }else{
        [SVProgressHUD show];
        [[ApConfigWifiManager shareAPManage] broadcast:self.wifiNameText.text wifiPwd:self.wifiPwdText.text suc:^{
            self.configWifiSuc = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                Toast(@"配网成功");
                [SVProgressHUD dismiss];
                WifiSettingViewController *wifiSetting = [[WifiSettingViewController alloc]init];
                wifiSetting.deviceName = self.prdName.text;
                wifiSetting.deviceCode = self.prdCode.text;
                wifiSetting.deviceId = self.prdId;
                [self.rt_navigationController pushViewController:wifiSetting animated:YES complete:nil];
            });
        } fail:^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                Toast(@"配网失败");
            });
        }];
    }
}
//-(void)connectWifi{
//    [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
//    SmartLinkExportObject *smartLinkUtl = [[SmartLinkExportObject alloc] init];
//    kWeakSelf;
//    smartLinkUtl.connectionSuccess = ^{
//        kStrongSelf;
//        Toast(@"配置成功");
//        [MBProgressHUD hideHUDForView:KeyWindow animated:YES];
//        [strongSelf bindDevice];
//    };
//    smartLinkUtl.connectionFailure = ^{
//        kStrongSelf;
//        Toast(@"配置结束");
//        [MBProgressHUD hideHUDForView:KeyWindow animated:YES];
//        [strongSelf bindDevice];
//    };
//    [smartLinkUtl connectWithSSID:self.wifiNameText.text  password:self.wifiPwdText.text];
//}
-(void)showWifiConfigErrorAlert{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否需要手动切换到设备热点" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url1 = [NSURL URLWithString:@"App-prefs:root=WIFI"];
        if ([[UIApplication sharedApplication] canOpenURL:url1]){
            [[UIApplication sharedApplication]openURL:url1 options:@{} completionHandler:nil];
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:nil];
    });
}
#pragma mark - instance
-(DeviceViewModel*)deviceInfoViewModel{
    if (!_deviceInfoViewModel) {
        _deviceInfoViewModel = [[DeviceViewModel alloc]init];
    }
    return _deviceInfoViewModel;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
